package com.example.administrator.helloas2_2_preview4;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class FocusImageView extends ImageView {

    private static final float MAX_ASPECT_RATIO_DEFORMATION_FRACTION = 0.01f;

    private static final float DEFAULT_RATIO = 16 / 9.0f;

    private float mWidthHeightRatio = DEFAULT_RATIO;

    public FocusImageView(Context context) {
        super(context);
    }

    public FocusImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int measuredWidth = getMeasuredWidth();

        int measuredHeight = getMeasuredHeight();

        if (measuredWidth != 0) {

            Log.i(getClass().getSimpleName(), " measuredWidth is " + measuredWidth);

            if (measuredHeight != 0) {
                final float viewAspectRatio = measuredWidth / (measuredHeight * 1.0f);

                float aspectDeformation = mWidthHeightRatio / viewAspectRatio - 1;

                if (Math.abs(aspectDeformation) <= MAX_ASPECT_RATIO_DEFORMATION_FRACTION) {
                    // We're within the allowed tolerance.
                    return;
                }
            }

            measuredHeight = (int) (measuredWidth / mWidthHeightRatio);

            setMeasuredDimension(measuredWidth, measuredHeight);
        } else {
            Log.i(getClass().getSimpleName(), " measuredWidth is zero , may be error ~");
        }
    }

    public void setWidthHeightRatio(float widthHeightRatio) {
        if (widthHeightRatio > 0) {
            this.mWidthHeightRatio = widthHeightRatio;
        }
    }
}
